import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "@/stores/useUser";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      redirect: "/dashboard/analysis",
      component: () => import("../views/mainView.vue"),
      children: [
        {
          path: "/dashboard",
          name: "dashboard",
          children: [
            {
              meta: {
                title: "分析页",
                fixed: true, //固定在标签栏
              },
              path: "/dashboard/analysis",
              name: "analysis",
              component: () =>
                import("../views/modules/dashboard/analysis.vue"),
            },
          ],
        },
        {
          path: "/sys",
          name: "sys",
          redirect: "/sys/menu",
          children: [
            {
              meta: {
                title: "地址管理",
              },
              path: "/sys/address",
              name: "address",
              component: () => import("../views/modules/sys/address.vue"),
            },
            {
              meta: {
                title: "菜单管理",
              },
              path: "/sys/menu",
              name: "menu",
              component: () => import("../views/modules/sys/menu.vue"),
            },
            {
              meta: {
                title: "角色管理",
              },
              path: "/sys/role",
              name: "role",
              component: () => import("../views/modules/sys/role.vue"),
            },
            {
              meta: {
                title: "系统用户",
              },
              path: "/sys/user",
              name: "user",
              component: () => import("../views/modules/sys/user.vue"),
            },
            {
              meta: {
                title: "部门管理",
              },
              path: "/sys/dept",
              name: "dept",
              component: () => import("../views/modules/sys/dept.vue"),
            },
          ],
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: import("@/views/login/login.vue"),
    },
  ],
});

router.beforeEach((to, from, next) => {
  // 返回 false 以取消导航
  const userStore = useUserStore();
  if (to.name !== "login" && !userStore.token) {
    next({ path: "/login" });
  } else {
    next();
  }
});

export default router;
